<template>
  <el-dialog
    v-model="visible"
    title="编辑测试用例"
    width="1400px"
    class="test-case-edit-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleBeforeClose"
    align-center
  >
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <div v-else class="dialog-content">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        class="test-case-form"
      >
        <div class="form-layout">
          <!-- 左侧主要内容区域 -->
          <div class="main-content">
            <!-- 标题 -->
            <div class="content-section">
              <el-form-item prop="title" class="title-item">
                <el-input
                  v-model="form.title"
                  placeholder="请输入测试用例标题"
                  maxlength="200"
                  show-word-limit
                  size="large"
                  class="title-input"
                />
              </el-form-item>
            </div>

            <!-- 测试用例内容（统一富文本编辑器） -->
            <div class="content-section">
              <div class="section-header">
                <span class="section-label">测试用例内容</span>
              </div>
              <div class="section-tip">
                <el-alert
                  type="info"
                  :closable="false"
                  show-icon
                  title="请按照模板格式填写：测试用例描述、前置条件、测试步骤（操作+预期结果）、预期结果（整体）、后置条件"
                />
              </div>
              <el-form-item prop="content" class="content-item">
                <RichTextEditor
                  v-model="formContent"
                  :height="500"
                  placeholder="测试用例内容..."
                />
              </el-form-item>
            </div>

            <!-- 关联信息（移到左侧） -->
            <div class="content-section">
              <div class="section-header">
                <el-icon><Link /></el-icon>
                <span class="section-label">关联信息</span>
              </div>
              <div class="association-grid">
                <el-form-item class="association-form-item">
                  <template #label>
                    <div class="form-label-with-icon">
                      <el-icon><Document /></el-icon>
                      <span>关联需求</span>
                    </div>
                  </template>
                  <el-select
                    v-model="form.requirement_id"
                    placeholder="选择需求（可选）"
                    filterable
                    clearable
                    style="width: 100%"
                    size="default"
                    :disabled="!form.project_id"
                  >
                    <el-option
                      v-for="req in availableRequirements"
                      :key="req.id"
                      :label="req.title"
                      :value="req.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item class="association-form-item">
                  <template #label>
                    <div class="form-label-with-icon">
                      <el-icon><List /></el-icon>
                      <span>关联任务</span>
                    </div>
                  </template>
                  <el-select
                    v-model="form.task_id"
                    placeholder="选择任务（可选）"
                    filterable
                    clearable
                    style="width: 100%"
                    size="default"
                    :disabled="!form.project_id"
                  >
                    <el-option
                      v-for="task in availableTasks"
                      :key="task.id"
                      :label="task.title"
                      :value="task.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item class="association-form-item">
                  <template #label>
                    <div class="form-label-with-icon">
                      <el-icon><Warning /></el-icon>
                      <span>关联缺陷</span>
                    </div>
                  </template>
                  <el-select
                    v-model="form.defect_id"
                    placeholder="选择缺陷（可选）"
                    filterable
                    clearable
                    style="width: 100%"
                    size="default"
                    :disabled="!form.project_id"
                    :loading="defectsLoading"
                  >
                    <el-option
                      v-for="defect in availableDefects"
                      :key="defect.id"
                      :label="defect.title"
                      :value="defect.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item class="association-form-item">
                  <template #label>
                    <div class="form-label-with-icon">
                      <el-icon><CollectionTag /></el-icon>
                      <span>关联版本</span>
                    </div>
                  </template>
                  <el-select
                    v-model="form.version_id"
                    placeholder="选择版本（可选）"
                    filterable
                    clearable
                    style="width: 100%"
                    size="default"
                    :disabled="!form.project_id"
                  >
                    <el-option
                      v-for="version in availableVersions"
                      :key="version.id"
                      :label="`${version.version_number} - ${version.name}`"
                      :value="version.id"
                    />
                  </el-select>
                </el-form-item>
              </div>
            </div>
          </div>

          <!-- 右侧侧边栏 -->
          <div class="sidebar-content">
            <!-- 项目信息 -->
            <div class="sidebar-section">
              <div class="section-header">
                <el-icon><Document /></el-icon>
                <span>项目信息</span>
              </div>
              <el-form-item class="sidebar-form-item">
                <template #label>
                  <div class="form-label-with-icon">
                    <el-icon><FolderOpened /></el-icon>
                    <span>项目</span>
                  </div>
                </template>
                <el-select
                  v-model="form.project_id"
                  placeholder="选择项目"
                  style="width: 100%"
                  filterable
                  size="default"
                  :loading="projectsLoading"
                  clearable
                >
                  <el-option
                    v-for="project in projects"
                    :key="project.id"
                    :label="project.name"
                    :value="project.id"
                  />
                </el-select>
              </el-form-item>
            </div>

            <!-- 人员信息 -->
            <div class="sidebar-section">
              <div class="section-header">
                <el-icon><User /></el-icon>
                <span>人员信息</span>
              </div>
              <el-form-item class="sidebar-form-item">
                <template #label>
                  <div class="form-label-with-icon">
                    <el-icon><UserFilled /></el-icon>
                    <span>负责人</span>
                  </div>
                </template>
                <el-select 
                  v-model="form.assignee_id" 
                  placeholder="选择负责人（可选）" 
                  style="width: 100%" 
                  size="default"
                  filterable
                  clearable
                  :loading="usersLoading"
                >
                  <el-option
                    v-for="user in users"
                    :key="user.id"
                    :label="user.name"
                    :value="user.id"
                  >
                    <div class="user-option">
                      <el-avatar :size="24" :src="user.avatar">
                        {{ user.name?.charAt(0) }}
                      </el-avatar>
                      <span>{{ user.name }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </div>

            <!-- 测试用例属性 -->
            <div class="sidebar-section">
              <div class="section-header">
                <el-icon><Setting /></el-icon>
                <span>测试用例属性</span>
              </div>
              <el-form-item prop="type" class="sidebar-form-item">
                <template #label>
                  <div class="form-label-with-icon">
                    <el-icon><CollectionTag /></el-icon>
                    <span>测试类型</span>
                  </div>
                </template>
                <el-select v-model="form.type" placeholder="选择类型" style="width: 100%" size="default">
                  <el-option
                    v-for="type in TEST_CASE_TYPE_OPTIONS"
                    :key="type.value"
                    :label="type.label"
                    :value="type.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="category" class="sidebar-form-item">
                <template #label>
                  <div class="form-label-with-icon">
                    <el-icon><Folder /></el-icon>
                    <span>测试分类</span>
                  </div>
                </template>
                <el-select v-model="form.category" placeholder="选择分类" style="width: 100%" size="default">
                  <el-option
                    v-for="category in TEST_CASE_CATEGORY_OPTIONS"
                    :key="category.value"
                    :label="category.label"
                    :value="category.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="status" class="sidebar-form-item">
                <template #label>
                  <div class="form-label-with-icon">
                    <el-icon><CircleCheck /></el-icon>
                    <span>状态</span>
                  </div>
                </template>
                <el-select 
                  v-model="form.status" 
                  placeholder="选择状态" 
                  style="width: 100%" 
                  size="default"
                  :loading="statesLoading"
                >
                  <el-option
                    v-for="state in testCaseStatusOptions"
                    :key="state.value"
                    :label="state.label"
                    :value="state.value"
                  >
                    <div class="status-option">
                      <span class="status-dot" :style="{ backgroundColor: state.color }"></span>
                      <span>{{ state.label }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="priority" class="sidebar-form-item">
                <template #label>
                  <div class="form-label-with-icon">
                    <el-icon><Sort /></el-icon>
                    <span>优先级</span>
                  </div>
                </template>
                <el-select v-model="form.priority" placeholder="选择优先级" style="width: 100%" size="default" :loading="loading">
                  <el-option
                    v-for="priority in testCasePriorityOptions"
                    :key="priority.value"
                    :label="priority.label"
                    :value="priority.value"
                  >
                    <div class="priority-option">
                      <span class="priority-dot" :style="{ backgroundColor: priority.color }"></span>
                      <span>{{ priority.label }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </div>


            <!-- 其他信息 -->
            <div class="sidebar-section">
              <div class="section-header">
                <el-icon><EditPen /></el-icon>
                <span>其他信息</span>
              </div>
              <el-form-item class="sidebar-form-item">
                <template #label>
                  <div class="form-label-with-icon">
                    <el-icon><Timer /></el-icon>
                    <span>预计时长（分钟）</span>
                  </div>
                </template>
                <el-input-number
                  v-model="form.estimated_duration"
                  :min="0"
                  :max="1440"
                  placeholder="预计执行时长"
                  style="width: 100%"
                  size="default"
                  controls-position="right"
                />
              </el-form-item>
              <el-form-item class="sidebar-form-item">
                <template #label>
                  <div class="form-label-with-icon">
                    <el-icon><Cpu /></el-icon>
                    <span>自动化状态</span>
                  </div>
                </template>
                <el-select v-model="form.automation_status" placeholder="选择状态" style="width: 100%" size="default" clearable>
                  <el-option
                    v-for="status in AUTOMATION_STATUS_OPTIONS"
                    :key="status.value"
                    :label="status.label"
                    :value="status.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item class="sidebar-form-item">
                <template #label>
                  <div class="form-label-with-icon">
                    <el-icon><PriceTag /></el-icon>
                    <span>标签</span>
                  </div>
                </template>
                <TagSelector
                  v-model="form.tags"
                  module-type="test_case"
                  placeholder="选择或创建标签"
                />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="handleClose" class="cancel-btn">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button type="primary" size="large" :loading="loading" @click="handleSubmit" class="submit-btn">
          <el-icon v-if="!loading"><CircleCheck /></el-icon>
          {{ loading ? '保存中...' : '保存修改' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Close, CircleCheck, Document, User, UserFilled, Setting, Link, EditPen, List, Warning, CollectionTag, Sort, Folder, FolderOpened, Timer, Cpu, PriceTag } from '@element-plus/icons-vue'

import { getTestCaseById, updateTestCase, type TestCaseUpdate, type TestCaseStatus } from '@/api/test-case'
import { useProjectStore } from '@/stores/project'
import { getUsers } from '@/api/user'
import { getRequirements } from '@/api/requirements'
import { getTasks } from '@/api/tasks'
import { getDefects } from '@/api/defect'
import { versionAPI } from '@/api/version'
import TagSelector from '@/components/common/TagSelector.vue'
import RichTextEditor from '@/components/common/EnhancedRichTextEditor.vue'
import { useTestCaseStates } from '@/composables/useTestCaseStates'
import { useTestCasePriorities } from '@/composables/useTestCasePriorities'
import { 
  TEST_CASE_TYPE_OPTIONS,
  TEST_CASE_CATEGORY_OPTIONS,
  AUTOMATION_STATUS_OPTIONS
} from '@/types/test-case'
import { formatTestCaseToTemplate, parseTemplateToTestCase } from '@/utils/test-case-template'

interface Props {
  modelValue: boolean
  testCaseId: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const projectsLoading = ref(false)
const usersLoading = ref(false)
const statesLoading = ref(false)

const projects = ref<Array<{ id: string; name: string }>>([])
const users = ref<Array<{ id: string; name: string; avatar?: string }>>([])
const availableRequirements = ref<Array<{ id: string; title: string }>>([])
const availableTasks = ref<Array<{ id: string; title: string }>>([])
const availableDefects = ref<Array<{ id: string; title: string }>>([])
const availableVersions = ref<Array<{ id: string; name: string; version_number: string }>>([])
const defectsLoading = ref(false)
// 标签功能已迁移到TagSelector组件，从标签管理模块获取系统标签

const { statusOptions: testCaseStatusOptionsFromComposable, loadStates: loadTestCaseStates } = useTestCaseStates()
const { priorityOptions: testCasePriorityOptionsFromComposable, fetchPriorities: fetchTestCasePriorities } = useTestCasePriorities()

// 在组件挂载时加载状态和优先级选项
onMounted(async () => {
  await loadTestCaseStates()
  await fetchTestCasePriorities()
})

const testCaseStatusOptions = computed(() => testCaseStatusOptionsFromComposable.value)
const testCasePriorityOptions = computed(() => testCasePriorityOptionsFromComposable.value)

const form = reactive<TestCaseUpdate & { test_steps: Array<{ step_number: number; action: string; expected_result: string }>; tags: string[] }>({
  title: '',
  description: '',
  preconditions: '',
  test_steps: [],
  expected_result: '',
  postconditions: '',
  type: 'functional',
  category: 'positive',
  status: undefined as TestCaseStatus | undefined,
  priority: 'medium',
  project_id: '',
    requirement_id: '',
    task_id: '',
    defect_id: '',
    version_id: '',
  assignee_id: '',
  tags: [],
  estimated_duration: undefined,
  automation_status: undefined
})

// 统一的富文本内容
const formContent = ref<string>('')

const rules: FormRules = {
  title: [
    { required: true, message: '请输入测试用例标题', trigger: ['blur', 'change'] },
    { min: 5, max: 200, message: '标题长度应在 5 到 200 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择测试类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择测试分类', trigger: 'change' }
  ]
  // 移除 content 字段的校验，允许内容为空
}

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loadTestCase = async () => {
  if (!props.testCaseId) return
  
  loading.value = true
  try {
    const testCase = await getTestCaseById(props.testCaseId) as any
    
    form.title = testCase.title || ''
    form.description = testCase.description || ''
    form.preconditions = testCase.preconditions || ''
    form.test_steps = (testCase.test_steps || []).map((step: any) => ({
      step_number: step.step_number || 0,
      action: step.action || '',
      expected_result: step.expected_result || ''
    }))
    form.expected_result = testCase.expected_result || ''
    form.postconditions = testCase.postconditions || ''
    form.type = testCase.type || 'functional'
    form.category = testCase.category || 'positive'
    form.status = testCase.status || ''
    form.priority = testCase.priority || 'medium'
    form.project_id = testCase.project_id || ''
    form.requirement_id = testCase.requirement_id || ''
    form.task_id = testCase.task_id || ''
    form.defect_id = testCase.defect_id || ''
    form.version_id = testCase.version_id || ''
    form.assignee_id = testCase.assignee_id || ''
    form.tags = testCase.tags || []
    form.estimated_duration = testCase.estimated_duration
    form.automation_status = testCase.automation_status
    
    // 初始化模板内容
    formContent.value = formatTestCaseToTemplate({
      description: form.description,
      preconditions: form.preconditions,
      test_steps: form.test_steps,
      expected_result: form.expected_result,
      postconditions: form.postconditions
    })
    
    await Promise.all([loadRequirements(), loadTasks(), loadDefects(), loadVersions()])
  } catch (error: any) {
    ElMessage.error(error.message || '加载测试用例失败')
  } finally {
    loading.value = false
  }
}

const projectStore = useProjectStore()

const loadProjects = async () => {
  projectsLoading.value = true
  try {
    const result = await projectStore.fetchProjects()
    projects.value = result.map((p: any) => ({
      id: p.value || p.id,
      name: p.label || p.name
    }))
  } catch (error) {
    console.error('加载项目列表失败:', error)
    projects.value = []
  } finally {
    projectsLoading.value = false
  }
}

// 加载用户列表（带缓存检查，避免重复加载）
const loadUsers = async () => {
  // 如果已有数据，直接返回
  if (users.value.length > 0) {
    return
  }
  
  // 如果正在加载，等待加载完成
  if (usersLoading.value) {
    return
  }
  
  usersLoading.value = true
  try {
    const result = await getUsers({ page: 1, size: 100 })
    // getUsers 返回的是 { items: User[], total: number, page: number, size: number } 格式
    if (result && typeof result === 'object' && 'items' in result && Array.isArray(result.items)) {
      users.value = result.items.map((u: any) => ({
        id: u.id || u._id,
        name: u.name || u.username || '',
        username: u.username || '',
        avatar: u.avatar
      }))
    } else if (Array.isArray(result)) {
      users.value = result.map((u: any) => ({
        id: u.id || u._id,
        name: u.name || u.username || '',
        username: u.username || '',
        avatar: u.avatar
      }))
    } else {
      users.value = []
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    users.value = []
  } finally {
    usersLoading.value = false
  }
}

const loadRequirements = async () => {
  if (!form.project_id) {
    availableRequirements.value = []
    return
  }
  try {
    const result = await getRequirements({ project_id: form.project_id })
    if (result && result.data) {
      if (Array.isArray(result.data)) {
        availableRequirements.value = result.data
      } else {
        availableRequirements.value = []
      }
    } else if (Array.isArray(result)) {
      availableRequirements.value = result
    } else {
      availableRequirements.value = []
    }
  } catch (error) {
    console.error('加载需求列表失败:', error)
    availableRequirements.value = []
  }
}

const loadTasks = async () => {
  if (!form.project_id) {
    availableTasks.value = []
    return
  }
  try {
    const response = await getTasks({ project_id: form.project_id })
    if (response.data && response.data.success) {
      const data = response.data.data
      if (Array.isArray(data)) {
        availableTasks.value = data
      } else if (data && typeof data === 'object' && 'items' in data) {
        availableTasks.value = Array.isArray(data.items) ? data.items : []
      } else {
        availableTasks.value = []
      }
    } else {
      availableTasks.value = []
    }
  } catch (error) {
    console.error('加载任务列表失败:', error)
    availableTasks.value = []
  }
}

const loadDefects = async () => {
  if (!form.project_id) {
    availableDefects.value = []
    return
  }
  defectsLoading.value = true
  try {
    const result = await getDefects({ project_id: form.project_id, page: 1, size: 100 })
    console.log('loadDefects 响应:', result)
    
    // getDefects 返回格式：{ items: Defect[], total: number, page: number, size: number }
    let defectsData: any[] = []
    
    if (result && typeof result === 'object') {
      if ('items' in result && Array.isArray(result.items)) {
        defectsData = result.items
      } else if (Array.isArray(result)) {
        defectsData = result
      }
    }
    
    availableDefects.value = defectsData.map((d: any) => ({
      id: d.id || d._id,
      title: d.title || ''
    }))
    console.log('loadDefects 处理后的缺陷列表:', availableDefects.value)
  } catch (error) {
    console.error('加载缺陷列表失败:', error)
    availableDefects.value = []
  } finally {
    defectsLoading.value = false
  }
}

const loadVersions = async () => {
  if (!form.project_id) {
    availableVersions.value = []
    return
  }
  try {
    const result = await versionAPI.getVersions({ project_id: form.project_id })
    availableVersions.value = Array.isArray(result) ? result : []
  } catch (error) {
    console.error('加载版本列表失败:', error)
  }
}

// 标签功能已迁移到TagSelector组件

watch(() => form.project_id, () => {
  loadRequirements()
  loadTasks()
  loadDefects()
  loadVersions()
})

watch(() => visible.value, (val) => {
  if (val && props.testCaseId) {
    // 在对话框打开时加载用户列表（按需加载）
    loadUsers()
    loadTestCase()
  }
})

const handleBeforeClose = (done: () => void) => {
  if (loading.value) {
    ElMessage.warning('正在保存中，请稍候...')
    return
  }
  ElMessageBox.confirm('确定要关闭吗？未保存的内容将丢失。', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    handleClose()
    done()
  }).catch(() => {})
}

const handleClose = () => {
  formRef.value?.resetFields()
  form.title = ''
  form.description = ''
  form.preconditions = ''
  form.test_steps = []
  form.expected_result = ''
  form.postconditions = ''
  form.requirement_id = ''
  form.task_id = ''
  form.defect_id = ''
  form.version_id = ''
  form.assignee_id = ''
  formContent.value = ''
  visible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  // 验证表单（只验证必填字段，不验证内容）
  try {
    await formRef.value.validate()
  } catch (error: any) {
    // 表单验证失败，显示第一个错误字段
    if (error && typeof error === 'object' && 'fields' in error) {
      const fields = error.fields as Record<string, any>
      const firstErrorField = Object.keys(fields)[0]
      if (firstErrorField && fields[firstErrorField] && fields[firstErrorField].length > 0) {
        const errorMessage = fields[firstErrorField][0].message
        ElMessage.warning(errorMessage || '请检查表单填写是否正确')
        // 滚动到第一个错误字段
        await formRef.value.scrollToField(firstErrorField)
      }
    }
    return
  }
  
  // 解析模板内容（即使为空也允许）
  try {
    const parsed = parseTemplateToTestCase(formContent.value || '')
    
    loading.value = true
    
    const submitData: TestCaseUpdate = {
      ...form,
      description: parsed.description || '',
      preconditions: parsed.preconditions || '',
      test_steps: (parsed.test_steps && parsed.test_steps.length > 0) 
        ? parsed.test_steps.map(step => ({
            step_number: step.step_number,
            action: step.action,
            expected_result: step.expected_result
          }))
        : [],
      expected_result: parsed.expected_result || '',
      postconditions: parsed.postconditions || ''
    }
    
    await updateTestCase(props.testCaseId, submitData)
    ElMessage.success('更新测试用例成功')
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '更新测试用例失败')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  // 只加载项目数据，状态和优先级数据应该由主页面提供（通过composable共享）
  // 用户列表在对话框打开时按需加载，避免重复调用API
  await loadProjects()
})
</script>

<style scoped lang="scss">
.test-case-edit-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #EBEEF5;
    background: linear-gradient(to bottom, #ffffff, #FAFBFC);
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 24px;
  }
  
  .loading-container {
    padding: 60px 40px;
    text-align: center;
  }
  
  .dialog-content {
    padding: 0;
    max-height: calc(80vh - 140px);
    overflow-y: auto;
    overflow-x: hidden;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f5f5f5;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #c0c4cc;
      border-radius: 3px;
      
      &:hover {
        background: #a8abb2;
      }
    }
  }
  
  .form-layout {
    display: flex;
    gap: 20px;
    min-height: 600px;
  }
  
  .main-content {
    flex: 1;
    min-width: 0;
    
    .content-section {
      margin-bottom: 24px;
      transition: all 0.3s ease;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid #EBEEF5;
        
        .el-icon {
          color: #409EFF;
          font-size: 18px;
        }
        
        .section-label {
          font-size: 15px;
          font-weight: 600;
          color: #303133;
          display: flex;
          align-items: center;
          gap: 8px;
          
          &::before {
            content: '';
            width: 3px;
            height: 16px;
            background: linear-gradient(to bottom, #409EFF, #66B1FF);
            border-radius: 2px;
          }
        }
      }
      
      .association-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 20px;
        margin-top: 16px;
        
        .association-form-item {
          margin-bottom: 0;
          
          .form-label-with-icon {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 13px;
            font-weight: 500;
            color: #606266;
            
            .el-icon {
              color: #909399;
              font-size: 14px;
            }
          }
          
          :deep(.el-form-item__label) {
            padding-bottom: 8px;
            line-height: 1.4;
          }
          
          :deep(.el-select) {
            .el-input__wrapper {
              transition: all 0.3s ease;
              
              &:hover {
                box-shadow: 0 0 0 1px #C0C4CC inset;
              }
              
              &.is-focus {
                box-shadow: 0 0 0 1px #409EFF inset;
              }
            }
          }
        }
      }
      
      .title-item {
        margin-bottom: 0;
        
        :deep(.el-form-item__content) {
          .el-input__wrapper {
            box-shadow: 0 0 0 1px #DCDFE6 inset;
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #C0C4CC inset;
            }
            
            &.is-focus {
              box-shadow: 0 0 0 1px #409EFF inset;
            }
          }
        }
        
        .title-input {
          font-size: 16px;
          font-weight: 500;
        }
      }
      
      .content-item {
        margin-bottom: 0;
        margin-top: 12px;
        
        :deep(.el-form-item__content) {
          border-radius: 6px;
          overflow: hidden;
          border: 1px solid #EBEEF5;
          transition: all 0.3s ease;
          
          &:hover {
            border-color: #C0C4CC;
          }
          
          &:focus-within {
            border-color: #409EFF;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
          }
        }
      }
      
      .section-tip {
        margin-bottom: 16px;
        
        :deep(.el-alert) {
          border-radius: 6px;
          border: none;
          background: #ECF5FF;
          padding: 12px 16px;
          
          .el-alert__title {
            font-size: 13px;
            color: #606266;
            line-height: 1.6;
          }
          
          .el-alert__icon {
            color: #409EFF;
          }
        }
      }
    }
  }
  
  .sidebar-content {
    width: 380px;
    flex-shrink: 0;
    position: sticky;
    top: 0;
    max-height: calc(80vh - 140px);
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f5f5f5;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #c0c4cc;
      border-radius: 3px;
      
      &:hover {
        background: #a8abb2;
      }
    }
    
      .sidebar-section {
      background: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%);
      border: 1px solid #EBEEF5;
      border-radius: 10px;
      padding: 22px;
      margin-bottom: 18px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.04);
      
      &:hover {
        box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
        border-color: #C0C4CC;
        transform: translateY(-1px);
      }
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-header {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 22px;
        padding-bottom: 14px;
        border-bottom: 2px solid #F0F2F5;
        font-weight: 600;
        font-size: 15px;
        color: #303133;
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          bottom: -2px;
          left: 0;
          width: 40px;
          height: 2px;
          background: linear-gradient(to right, #409EFF, transparent);
          border-radius: 1px;
        }
        
        .el-icon {
          color: #409EFF;
          font-size: 18px;
          transition: transform 0.3s ease;
        }
        
        &:hover .el-icon {
          transform: scale(1.1);
        }
      }
      
      .title-item {
        margin-bottom: 0;
        
        :deep(.el-form-item__content) {
          .el-input__wrapper {
            box-shadow: 0 0 0 1px #DCDFE6 inset;
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #C0C4CC inset;
            }
            
            &.is-focus {
              box-shadow: 0 0 0 1px #409EFF inset;
            }
          }
        }
        
        :deep(.el-form-item__error) {
          padding-top: 6px;
          color: #F56C6C;
          font-size: 12px;
          line-height: 1.4;
        }
      }
      
      .sidebar-form-item {
        margin-bottom: 20px;
        transition: all 0.2s ease;
        padding: 12px;
        border-radius: 6px;
        background: #FFFFFF;
        border: 1px solid transparent;
        
        &:hover {
          background: #F8F9FA;
          border-color: #E4E7ED;
        }
        
        &:last-child {
          margin-bottom: 0;
        }
        
        :deep(.el-form-item__label) {
          font-size: 13px;
          font-weight: 600;
          color: #606266;
          margin-bottom: 12px;
          padding: 0;
          line-height: 1.5;
          display: flex;
          align-items: center;
          gap: 6px;
          
          &::before {
            content: '';
            width: 3px;
            height: 12px;
            background: #DCDFE6;
            border-radius: 2px;
            transition: background 0.3s ease;
          }
        }
        
        &:hover :deep(.el-form-item__label::before) {
          background: #409EFF;
        }
        
        :deep(.el-form-item__error) {
          padding-top: 6px;
          color: #F56C6C;
          font-size: 12px;
          line-height: 1.4;
          position: relative;
          margin-top: 0;
          padding-left: 4px;
        }
        
        :deep(.el-select),
        :deep(.el-input),
        :deep(.el-input-number) {
          .el-input__wrapper {
            transition: all 0.3s ease;
            border-radius: 6px;
            background: #FFFFFF;
            
            &:hover {
              box-shadow: 0 0 0 1px #C0C4CC inset;
              background: #FAFBFC;
            }
            
            &.is-focus {
              box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) inset, 0 0 0 1px #409EFF inset;
              background: #FFFFFF;
            }
          }
        }
        
        :deep(.el-select__tags) {
          .el-tag {
            background: #ECF5FF;
            border-color: #B3D8FF;
            color: #409EFF;
            border-radius: 4px;
          }
        }
        
        :deep(.el-select__selected-item) {
          display: flex;
          align-items: center;
          gap: 6px;
        }
        
        .user-option {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 4px 0;
          
          .el-avatar {
            flex-shrink: 0;
            border: 1px solid #E4E7ED;
          }
          
          span {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        
        .status-option,
        .priority-option {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 4px 0;
          
          .status-dot,
          .priority-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            flex-shrink: 0;
            box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.8), 0 0 0 3px currentColor;
          }
          
          span:last-child {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        
        .form-label-with-icon {
          display: flex;
          align-items: center;
          gap: 6px;
          
          .el-icon {
            color: #909399;
            font-size: 14px;
          }
        }
        
        // 验证错误状态的样式
        &.is-error {
          border-color: #F56C6C;
          background: #FEF0F0;
          
          :deep(.el-form-item__label::before) {
            background: #F56C6C;
          }
          
          :deep(.el-select .el-input__wrapper),
          :deep(.el-input .el-input__wrapper) {
            box-shadow: 0 0 0 1px #F56C6C inset;
            background: #FFFFFF;
            
            &:hover,
            &.is-focus {
              box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2) inset, 0 0 0 1px #F56C6C inset;
            }
          }
        }
      }
      
      .form-tip {
        font-size: 12px;
        color: #909399;
        margin-top: 8px;
        padding-left: 8px;
        line-height: 1.5;
        display: flex;
        align-items: center;
        gap: 4px;
        
        &::before {
          content: 'ℹ';
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 24px;
    border-top: 1px solid #EBEEF5;
    background: #FAFBFC;
    margin: 0 -24px -24px -24px;
    
    .cancel-btn,
    .submit-btn {
      padding: 10px 24px;
      font-size: 14px;
      border-radius: 6px;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
  }
}
</style>

